package com.vrland.web.front;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
		/*
		 * auth.inMemoryAuthentication().withUser("user").password("password")
		 * .roles("USER").and().withUser("admin").password("password")
		 * .roles("ADMIN");
		 */
		auth.jdbcAuthentication().dataSource(dataSource)
				.authoritiesByUsernameQuery(getAuthoritiesQuery())
				.usersByUsernameQuery(getUserQuery())
				.passwordEncoder(passwordEncoder);
	}

	private String getUserQuery() {
		return "SELECT login_name as username, password, enabled FROM user WHERE login_name=?";
	}

	private String getAuthoritiesQuery() {
		return "SELECT login_name as username, role as authority FROM user WHERE login_name=?";
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/admin/**").hasAuthority("ADMIN")
				.anyRequest().permitAll().and().formLogin();
	}

}